package respberry

import (
	"fmt"
	"os/exec"
	"regexp"
	"runtime"
	"strings"
)

// 如果当前系统是树莓派就返回树莓派的cpu序列号
func RaspberryCpuId() string {
	sysType := runtime.GOOS

	if sysType == "linux" {
		/**
		cat /proc/cpuinfo 树莓派类似输出
		processor       : 0
		model name      : ARMv7 Processor rev 3 (v7l)
		BogoMIPS        : 270.00
		Features        : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
		CPU implementer : 0x41
		CPU architecture: 7
		CPU variant     : 0x0
		CPU part        : 0xd08
		CPU revision    : 3

		processor       : 1
		model name      : ARMv7 Processor rev 3 (v7l)
		BogoMIPS        : 270.00
		Features        : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
		CPU implementer : 0x41
		CPU architecture: 7
		CPU variant     : 0x0
		CPU part        : 0xd08
		CPU revision    : 3

		processor       : 2
		model name      : ARMv7 Processor rev 3 (v7l)
		BogoMIPS        : 270.00
		Features        : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
		CPU implementer : 0x41
		CPU architecture: 7
		CPU variant     : 0x0
		CPU part        : 0xd08
		CPU revision    : 3

		processor       : 3
		model name      : ARMv7 Processor rev 3 (v7l)
		BogoMIPS        : 270.00
		Features        : half thumb fastmult vfp edsp neon vfpv3 tls vfpv4 idiva idivt vfpd32 lpae evtstrm crc32
		CPU implementer : 0x41
		CPU architecture: 7
		CPU variant     : 0x0
		CPU part        : 0xd08
		CPU revision    : 3

		Hardware        : BCM2711
		Revision        : b03140
		Serial          : 1000000047e1d62e
		Model           : Raspberry Pi Compute Module 4 Rev 1.0
		*/
		out, err := exec.Command("cat", "/proc/cpuinfo").Output()

		if err != nil {
			panic(err)
		}
		//fmt.Println("out=="+string(out))

		str := string(out)

		//判断是否有 Raspberry 字样来判断是否是树莓派
		reg1, _ := regexp.Compile("Raspberry")
		ok := reg1.MatchString(str)
		if ok == false {
			fmt.Println("当前为linux系统,但并非为树莓派系统!")
			return ""
		}

		//reg,_ := regexp.Compile("Serial          : [A-Za-z0-9]+")
		//Serial          : 1000000047e1d62e
		reg, _ := regexp.Compile("Serial.+")
		s := reg.FindString(str)
		fmt.Println("match==" + s)
		b := strings.Split(s, ": ")
		fmt.Println("正常获取到树莓派cpu序列号=" + b[1])
		return b[1]
	}

	if sysType == "windows" {
		fmt.Println("windows系统，非树莓派")
		return ""
	}
	return ""
}
